package com.qiandw.security.service;

import com.qiandw.entity.security.Role;
import com.qiandw.repo.security.UserRepo;
import com.qiandw.security.entity.UserDetailImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.core.userdetails.MapReactiveUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author coxx
 */

@Service
public class ServerUserDetailServiceImpl extends MapReactiveUserDetailsService {

    @Autowired
    public ServerUserDetailServiceImpl(UserRepo userRepo) {
        super(insertUsers(userRepo));
    }

    public static Collection<UserDetails> insertUsers(UserRepo userRepo){
        List<com.qiandw.entity.security.User> users = userRepo.findAll();
        users.add(initSystemUser());
        return users.stream().map(UserDetailImpl::new).collect(Collectors.toList());
    }


    public synchronized static UserDetailImpl initSystemUser(){
        com.qiandw.entity.security.User user = new com.qiandw.entity.security.User();
        user.setEducation("大学");
        user.setId(UUID.randomUUID().toString());
        user.setIdNo("522601199406170055");
        user.setIsEnabled(true);
        user.setMail("coxx@vip.qq.com");
        user.setMobile("15761627327");
        user.setPassword("{MD5}{SS/+ikPQDwvdBtm/rmvyMd+xb02AZ5ESyjf0ybKmT8M=}6ea5a0b27c03066de7b857cd88870364");
        user.setUsername("coxx");

        Role role = new Role();
        role.setDescription("系统管理员角色");
        role.setStatus(1);
        role.setId(UUID.randomUUID().toString());
        role.setName("sysAdmin");
        user.setRoles(Collections.singletonList(role));

        return new UserDetailImpl(user);
    }
}
